﻿using System;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;


namespace TrainingsApp.Helper 
{
    public class JsonHelper
    {
        /// <summary>
        /// Json序列化,用于发送到客户端
        /// </summary>
        public static string ToJsJson(object item)
        {
            if (item==null) return "null";
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType());

            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, item);
                    StringBuilder sb = new StringBuilder();
                    sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
                    return sb.ToString();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 另一种Json序列化
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToStdJson(object obj)
        {
            if (obj==null) return "";
            try
            {
                JavaScriptSerializer jss = new JavaScriptSerializer();
                string s = jss.Serialize(obj);
                return s;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}